package com.wp.file.adminMGT.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wp.file.adminMGT.pojo.Admin;
import com.wp.file.adminMGT.pojo.EcharsOne;
import com.wp.file.adminMGT.service.AdminService;
import com.wp.file.common.BaseContext;
import com.wp.file.common.R;
import com.wp.file.pojo.User;
import com.wp.file.pojo.Warehouse;
import com.wp.file.pojo.vo.Share;
import com.wp.file.service.UserService;
import com.wp.file.service.WarehouseService;
import com.wp.file.utils.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/management")
public class ManagementController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private WarehouseService warehouseService;

    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpSession session, HttpServletResponse response) {
        log.info("管理员开始登录:" + map.toString());
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return R.error("账号或密码不能为空!");
        }
        LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Admin::getUsername, username);
        Admin admin = adminService.getOne(lqw);
        if (admin == null) {
            //没管理就返回
            return R.error("管理员账号不存在!");
        }
        if (!admin.getPassword().equals(password)) {
            //密码错误返回
            return R.error("密码错误!");
        }
        //登录成功 生成token返回
        Map<String, String> tmap = new HashMap<>();
        tmap.put("userId", admin.getId().toString());
        tmap.put("username", admin.getUsername().toString());
        String token = JwtTool.getJWT(tmap);
        response.setHeader("Authorization", token);
        //设置token有效期
        redisTemplate.opsForValue().set(username + "Authorization", token, 1, TimeUnit.DAYS);
        BaseContext.setCurrentAdminId(admin.getId());
        return R.success("欢迎登录成功!" + username);
    }

    @PostMapping("/loginout")
    public R<String> loginout(@RequestHeader("Authorization") String auth) {
        String username = JwtTool.parseJWT(auth).getClaims().get("username").asString();
        redisTemplate.delete(username + "Authorization");
        return R.success(username + "退出成功!");
    }

    @GetMapping("/getusername")
    public R<String> getinfo() {
        Long currentId = BaseContext.getCurrentAdminId();
        Admin admin = adminService.getById(currentId);
        return R.success(admin.getUsername().toString());
    }

    @GetMapping("/getalladmin")
    public R<List<Admin>> getAllAdmin() {
        List<Admin> adminList = adminService.list();
        return R.success(adminList);
    }

    @PostMapping("/admin/add")
    public R<String> adminAdd(@RequestBody Map map) {
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        Integer issystem = (Integer) map.get("issystem");
        LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Admin::getUsername, username);
        Admin adminone = adminService.getOne(lqw);
        if (adminone != null) {
            return R.error("该用户已存在!");
        }
        Long currentId = BaseContext.getCurrentAdminId();
        Admin admin = adminService.getById(currentId);
        if (admin.getIsSystem() != 1) {//不是顶级管理员时
            return R.error("本账户权限为普通管理员,权限较低无法添加管理员账户");
        }
        Admin admin1 = new Admin();admin1.setUsername(username);
        admin1.setPassword(password);admin1.setIsSystem(issystem);
        adminService.save(admin1);
        return R.success("添加管理员用户成功!--"+username);
    }

    @PutMapping("/changeadminpass")
    public R<String> changeAdminPass(@RequestBody Map map) {
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        Long currentId = BaseContext.getCurrentAdminId();
        Admin admin = adminService.getById(currentId);
        if (admin.getIsSystem() == 0) {//普通管理员没资格
            return R.error("普通管理员无资格修改任何管理员的密码!");
        }
        LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Admin::getUsername, username);
        Admin one = adminService.getOne(lqw);
        if (one == null) {
            return R.error("该用户" + username + "不存在!");
        }
        one.setPassword(password);
        adminService.updateById(one);
        return R.success("修改密码成功!");
    }

    @DeleteMapping("/deleteadmin")
    public R<String> deleteAdminOne(@RequestBody Map map) {
        String username = map.get("username").toString();
        Long currentId = BaseContext.getCurrentAdminId();
        Admin admin = adminService.getById(currentId);
        if (admin.getIsSystem() == 0) {//普通管理员没资格
            return R.error("普通管理员无资格删除任何管理员的账户!");
        }
        LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Admin::getUsername, username);
        Admin one = adminService.getOne(lqw);
        if (one == null) {
            return R.error("该管理员账户" + username + "不存在!");
        }
        adminService.removeById(one.getId());
        return R.success("该管理员账户已删除!");
    }

    @GetMapping("/users/page")
    public R<Page> getUserList(int currentPage, int pageSize, String selectName) {
        log.info("page = {},pageSize = {},name = {}", currentPage, pageSize, selectName);
        //构造分页构造器
        Page pageInfo = new Page(currentPage, pageSize);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotEmpty(selectName), User::getEmail, selectName);
        lqw.orderByDesc(User::getCreateTime);
        userService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /**
     * 修改用户传输权限
     */
    @PutMapping("/users/changeper/{id}/{action}")
    public R<Integer> changePer(@PathVariable("id") Long id,
                                @PathVariable("action") String action) {
        log.info("id={},action={}", id, action);
        //改变ban
        User user = userService.getById(id);
        if (user == null) {
            return R.error("该用户参数错误!");
        }
        int ban = 0;
        if (action.equals("disable")) {
            ban = 1;
        } else if (action.equals("enable")) {
            ban = 0;
        }
        if (user.getBanTransfer() == ban) {
            return R.error("该用户参数错误!");
        }
        user.setBanTransfer(ban);
        userService.updateById(user);
        return R.success(ban);
    }

    /**
     * 查看所有用户分享信息
     * @return
     */
    @GetMapping("/share/list")
    public R<List<Share>> getShareList(){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User::getId);
        List<Object> userIds = userService.listObjs(wrapper);
        List<Share> allValues = new ArrayList<>();  // 定义一个新的 List 对象
        for (Object userId : userIds) {
            Map<Object, Share> hashData = redisTemplate.opsForHash().entries(userId.toString());
            Collection<Share> values = hashData.values();
            allValues.addAll(values);  // 将 values 添加到 allValues 集合中
        }
        return R.success(allValues);
    }

    /**
     * 查看分享人
     */
    @GetMapping("/share/user")
    public R<String> getShareUserInfo(Long shareId){
        Set<String> allKeys = redisTemplate.keys("*");
        HashOperations<String, Object, Object> hashOps = redisTemplate.opsForHash();
        for (String key : allKeys) {
            if (redisTemplate.type(key).equals(DataType.HASH)) { // 判断当前 key 是否为 hash 类型
                Set<Object> fieldKeys = hashOps.keys(key);
                if (fieldKeys.contains(shareId.toString())) { // 如果 fieldKeys 中包含 shareId，则说明存在对应的 hash 表
                    return R.success(getUserInfo(key));
                }
            }
        }
        return R.error("该分享人未知!");
    }

    @GetMapping("/disk/storagestatus")
    public R<List<EcharsOne>> getDiskStorageStatus(){
        LambdaQueryWrapper<Warehouse> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Warehouse::getSort,1);//文档
        LambdaQueryWrapper<Warehouse> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(Warehouse::getSort,2);//图像
        LambdaQueryWrapper<Warehouse> lqw3 = new LambdaQueryWrapper<>();
        lqw3.eq(Warehouse::getSort,3);//音频
        LambdaQueryWrapper<Warehouse> lqw4 = new LambdaQueryWrapper<>();
        lqw4.eq(Warehouse::getSort,4);//视频

        LambdaQueryWrapper<Warehouse> lqwOther = new LambdaQueryWrapper<>();
        lqwOther.notIn(Warehouse::getSort, Arrays.asList(0, 1, 2, 3, 4));//其他

        List<EcharsOne> list = new ArrayList<>();
        list.add(new EcharsOne("文档",warehouseService.count(lqw1)));
        list.add(new EcharsOne("图像",warehouseService.count(lqw2)));
        list.add(new EcharsOne("音频",warehouseService.count(lqw3)));
        list.add(new EcharsOne("视频",warehouseService.count(lqw4)));
        list.add(new EcharsOne("其他",warehouseService.count(lqwOther)));
        return R.success(list);
    }

    private String getUserInfo(String key){
        Long userId = Long.parseLong(key);
        User user = userService.getById(userId);
        return user.getEmail();
    }

    //取消分享
    @GetMapping("/share/cancel")
    public R<String> deleteShare(Long shareId) {
        Set<String> allKeys = redisTemplate.keys("*");
        HashOperations<String, Object, Object> hashOps = redisTemplate.opsForHash();

        for (String key : allKeys) {
            if (redisTemplate.type(key).equals(DataType.HASH)) { // 检查当前键是否为哈希类型
                Set<Object> fieldKeys = hashOps.keys(key);
                if (fieldKeys.contains(shareId.toString())) { // 如果fieldKeys包含shareId，则删除特定字段
                    hashOps.delete(key, shareId.toString());
                    return R.success("取消分享成功！");
                }
            }
        }

        // 处理未在任何哈希中找到shareId的情况
        return R.error("未找到ShareId。");
    }

}
